﻿/*****************************************************************
 * Copyright (C) Newegg Corporation. All rights reserved.
 * 
 * Author       :  Bill Li (Bill.S.Li@newegg.com)
 * Create Date  :  
 * Usage        :  
 *
 * RevisionHistory
 * Date         Author               Description
 * 
*****************************************************************/
using System;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Xml;

namespace TemplateEngine.TranslateCommand
{
    internal class ShowTranslate : ITranslate
    {
        private static Regex s_functionReg;

        static ShowTranslate()
        {
            s_functionReg = new Regex("[a-zA-Z]+[\\s]*\\([^<>()]*\\)", RegexOptions.Compiled);
        }

        public string Translate(TemplateNode node, XmlNode xmlNode)
        {
            string innerStr = node.InnerStr;
            innerStr = innerStr.Trim();
            string result = string.Empty;

            // 判断内置函数
            if (s_functionReg.IsMatch(innerStr))
            {
                Match match;
                while ((match = s_functionReg.Match(innerStr)) != Match.Empty)
                {
                    string functionName = match.Value;
                    string tmp = FunctionHelper.ExecuteFunction(functionName, xmlNode, node).ToString();
                    innerStr = innerStr.Replace(functionName, tmp);
                }

                result = innerStr;
            }
            else   // 判断节点显示
            {
                XmlNode hit = xmlNode.SelectSingleNode(innerStr);
                if (hit != null)
                {
                    result = hit.InnerText;
                }
            }

            return result;
        }
    }
}
